FairCalendarOverviewFactory.create   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 58
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 43
dl 0
loc 58
rs 7.448
c 0
b 0
f 0
cc 7

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
import { Inject } from '@nestjs/common';
2
import { FairCalendarView } from 'src/Application/FairCalendar/View/FairCalendarView';
3
import { CooperativeNotFoundException } from '../Settings/Repository/CooperativeNotFoundException';
4
import { ICooperativeRepository } from '../Settings/Repository/ICooperativeRepository';
5
import { ICalendarOverview } from './ICalendarOverview';
6
import { EventType } from './Event.entity';
7
8
export class FairCalendarOverviewFactory {
9
  constructor(
10
    @Inject('ICooperativeRepository')
11
    private readonly cooperativeRepository: ICooperativeRepository
12
  ) {}
13
14
  public async create(items: FairCalendarView[]): Promise<ICalendarOverview> {
15
    const cooperative = await this.cooperativeRepository.find();
16
    if (!cooperative) {
17
      throw new CooperativeNotFoundException();
18
    }
19
20
    const overviewInDays: ICalendarOverview = {
21
      mission: {
22
        days: 0,
23
        details: []
24
      },
25
      dojo: {
26
        days: 0
27
      },
28
      formationConference: {
29
        days: 0
30
      },
31
      leave: {
32
        days: 0
33
      },
34
      support: {
35
        days: 0
36
      },
37
      other: {
38
        days: 0
39
      }
40
    };
41
42
    for (const { time, type: itemType, project } of items) {
43
      const type = itemType.startsWith('leave_') ? 'leave' : itemType;
44
      const days = time / cooperative.getDayDuration();
45
46
      if (overviewInDays[type]) {
47
        overviewInDays[type].days =
48
          Math.round((overviewInDays[type].days + days) * 100) / 100;
49
50
        if (type === EventType.MISSION) {
51
          const missionDetail = overviewInDays[type].details.find(
52
            ({ label }) => label === project.name
53
          );
54
55
          if (missionDetail) {
56
            missionDetail.days =
57
              Math.round(
58
                (missionDetail.days + Math.round(days * 100) / 100) * 100
59
              ) / 100;
60
          } else {
61
            overviewInDays[type].details.push({
62
              days,
63
              label: project.name
64
            });
65
          }
66
        }
67
      }
68
    }
69
70
    return overviewInDays;
71
  }
72
}
73